<template>
  <div class="withdrawal-statistics">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>提现统计</span>
        <el-button 
          type="success" 
          size="small" 
          icon="el-icon-download"
          style="float: right;"
          @click="exportData"
          :loading="exportLoading">
          导出CSV
        </el-button>
      </div>

      <!-- 筛选区域 -->
      <div class="filter-section">
        <el-form :inline="true" :model="filterForm" size="small">
          <el-form-item label="渠道">
            <el-select 
              v-model="filterForm.channel" 
              placeholder="请选择渠道" 
              style="width: 150px;"
              clearable>
              <el-option
                v-for="item in channelOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="日期范围">
            <el-date-picker
              v-model="filterForm.dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd"
              style="width: 240px;"
            ></el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleToday">今日</el-button>
            <el-button type="primary" @click="handleYesterday">昨日</el-button>
            <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
            <el-button icon="el-icon-refresh" @click="resetFilter">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <el-table
        :data="withdrawalData"
        border
        style="width: 100%"
        :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
        v-loading="loading"
      >
        <el-table-column prop="time" label="日期" width="120"></el-table-column>
        <el-table-column prop="channel" label="渠道" width="80"></el-table-column>
        <el-table-column prop="pay_rp" label="充值金额rp" width="120"></el-table-column>
        <el-table-column prop="cashout_rp" label="提现rp" width="120"></el-table-column>
        <el-table-column prop="diff_rp" label="差额rp" width="120"></el-table-column>
        <el-table-column prop="diff_rmb_rp" label="差额折合￥" width="120"></el-table-column>
        <el-table-column prop="diff_dollar_rp" label="差额折合$" width="120"></el-table-column>
      </el-table>
      
      <div class="pagination-container">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </div>
    </el-card>
  </div>
</template>

<script>
import { cashoutStatistic } from '@/api/user'
import { exportDataToCsv } from '@/utils/export'
import channelMixin from '@/mixins/channelMixin'

export default {
  mixins: [channelMixin],
  name: 'WithdrawalStatistics',
  data() {
    return {
      withdrawalData: [],
      loading: false,
      currentPage: 1,
      pageSize: 10,
      total: 0,
      exportLoading: false,
      filterForm: {
        channel: null,
        dateRange: []
      }
    }
  },
  
  mounted() {
    // 渠道选项通过mixin自动加载
    this.fetchData()
  },
  
  methods: {
    handleSizeChange(val) {
      this.pageSize = val
      this.currentPage = 1
      this.fetchData()
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.fetchData()
    },
    async fetchData() {
      this.loading = true
      try {
        const params = {
          page: this.currentPage,
          page_size: this.pageSize,
          channel: this.formatChannelParam(this.filterForm.channel),
          begin_time: this.filterForm.dateRange && this.filterForm.dateRange[0] ? this.filterForm.dateRange[0] : '',
          end_time: this.filterForm.dateRange && this.filterForm.dateRange[1] ? this.filterForm.dateRange[1] : ''
        }
        
        const response = await cashoutStatistic(params)
        
        if (response && response.code === 0) {
          // 处理可能的数据结构差异
          let records = []
          if (response.data && response.data.cashouts && Array.isArray(response.data.cashouts)) {
            records = response.data.cashouts
          } else if (response.data && response.data.records && Array.isArray(response.data.records)) {
            records = response.data.records
          } else if (response.data && response.data.list && Array.isArray(response.data.list)) {
            records = response.data.list
          } else if (Array.isArray(response.data)) {
            records = response.data
          } else if (response.data && typeof response.data === 'object') {
            for (let key in response.data) {
              if (Array.isArray(response.data[key])) {
                records = response.data[key]
                break
              }
            }
          }
          
          this.withdrawalData = records
          
          // 处理分页信息
          if (response.data && response.data.total_page) {
            this.total = response.data.total_page * this.pageSize
          } else if (response.data && response.data.total) {
            this.total = response.data.total
          } else {
            this.total = records.length
          }
        } else {
          this.$message.error(response.msg || response.message || '获取数据失败')
        }
      } catch (error) {
        console.error('获取提现统计数据失败:', error)
        this.$message.error('获取数据失败')
      } finally {
        this.loading = false
      }
    },
    async exportData() {
      this.exportLoading = true
      try {
        const params = {
          channel: this.formatChannelParam(this.filterForm.channel),
          begin_time: this.filterForm.dateRange && this.filterForm.dateRange[0] ? this.filterForm.dateRange[0] : '',
          end_time: this.filterForm.dateRange && this.filterForm.dateRange[1] ? this.filterForm.dateRange[1] : '',
          page: 1,
          page_size: 10000
        }
        
        const response = await cashoutStatistic(params)
        
        // 处理数据结构差异
        let allData = []
        if (response.data && response.data.cashouts && Array.isArray(response.data.cashouts)) {
          allData = response.data.cashouts
        } else if (response.data && Array.isArray(response.data)) {
          allData = response.data
        } else if (response.data && typeof response.data === 'object') {
          for (let key in response.data) {
            if (Array.isArray(response.data[key])) {
              allData = response.data[key]
              break
            }
          }
        }
        
        const columns = [
          { prop: 'time', label: '日期' },
          { prop: 'channel', label: '渠道' },
          { prop: 'pay_rp', label: '充值金额rp' },
          { prop: 'cashout_rp', label: '提现rp' },
          { prop: 'diff_rp', label: '充值-提现=差额' },
          { prop: 'diff_rmb_rp', label: '差额折合￥' },
          { prop: 'diff_dollar_rp', label: '差额折合$' }
        ]
        
        const now = new Date()
        const dateStr = now.getFullYear() + 
          String(now.getMonth() + 1).padStart(2, '0') + 
          String(now.getDate()).padStart(2, '0') + '_' +
          String(now.getHours()).padStart(2, '0') + 
          String(now.getMinutes()).padStart(2, '0')
        
        const fileName = `提现统计_${dateStr}.csv`
        exportDataToCsv(allData, columns, fileName)
        this.$message.success('导出成功！')
      } catch (error) {
        this.$message.error('导出失败')
        console.error(error)
      } finally {
        this.exportLoading = false
      }
    },
    handleSearch() {
      this.currentPage = 1
      this.fetchData()
    },
    resetFilter() {
      this.filterForm.channel = null
      this.filterForm.dateRange = []
      this.currentPage = 1
      this.fetchData()
    },
    handleToday() {
      const today = new Date()
      this.filterForm.dateRange = [
        `${today.getFullYear()}-${String(today.getMonth() + 1).padStart(2, '0')}-${String(today.getDate()).padStart(2, '0')}`,
        `${today.getFullYear()}-${String(today.getMonth() + 1).padStart(2, '0')}-${String(today.getDate()).padStart(2, '0')}`
      ]
      this.handleSearch()
    },
    handleYesterday() {
      const today = new Date()
      const yesterday = new Date(today)
      yesterday.setDate(today.getDate() - 1)
      this.filterForm.dateRange = [
        `${yesterday.getFullYear()}-${String(yesterday.getMonth() + 1).padStart(2, '0')}-${String(yesterday.getDate()).padStart(2, '0')}`,
        `${yesterday.getFullYear()}-${String(yesterday.getMonth() + 1).padStart(2, '0')}-${String(yesterday.getDate()).padStart(2, '0')}`
      ]
      this.handleSearch()
    }
  }
}
</script>

<style scoped>
.withdrawal-statistics {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.filter-section {
  margin-bottom: 20px;
}
</style> 